﻿using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;

namespace PlaceOrder_Server.Helper
{


    public class GlobalHotKeyManager
    {
        private const int HOTKEY_ID = 9000;
        private const uint MOD_CTRL = 0x0002; // Control 键
        private const uint VK_M = 0x4D; // M 键

        [DllImport("user32.dll")]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

        [DllImport("user32.dll")]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        private IntPtr _windowHandle;
        private HwndSource _source;

        public event Action OnHotKeyPressed;

        public void RegisterGlobalHotKey(Window window)
        {
            _windowHandle = new WindowInteropHelper(window).Handle;
            _source = HwndSource.FromHwnd(_windowHandle);
            _source.AddHook(HwndHook);

            RegisterHotKey(_windowHandle, HOTKEY_ID, MOD_CTRL, VK_M);
        }

        public void UnregisterGlobalHotKey()
        {
            _source.RemoveHook(HwndHook);
            UnregisterHotKey(_windowHandle, HOTKEY_ID);
        }

        private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            const int WM_HOTKEY = 0x0312;

            if (msg == WM_HOTKEY && wParam.ToInt32() == HOTKEY_ID)
            {
                OnHotKeyPressed?.Invoke();
                handled = true;
            }

            return IntPtr.Zero;
        }
    }

}
